package com.java.example.ui.update

import java.io.File
import java.util.concurrent.Executors
import java.util.concurrent.ThreadPoolExecutor

class UpdateManager private constructor() {
    private val threadPoolExecutor = Executors.newCachedThreadPool() as ThreadPoolExecutor
    private var request: UpdateDownloadRequest? = null

    fun startDownloads(downloadUrl: String?, localPath: String, listener: UpdateDownloadListener?) {
//        if (request != null) {
//            return
//        }
        checkLocalFilePath(localPath)
        request = UpdateDownloadRequest(downloadUrl!!, localPath, listener!!)
        val future = threadPoolExecutor.submit(request)
    }

    /**
     * 检查文件路径是否存在
     * @param path
     */
    private fun checkLocalFilePath(path: String) {
//        Log.e("tag", path);
        val dir = File(path.substring(0, path.lastIndexOf("/") + 1))
        if (!dir.exists()) {
            dir.mkdir()
        }
        val file = File(path)
        if (!file.exists()) {
            try {
                file.createNewFile()
            } catch (e: Exception) {
            }
        }
    }

    companion object {
        var instance: UpdateManager
            private set

        init {
            instance = UpdateManager()
        }
    }
}
